package com.qili.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.base.controller.BaseController;
import com.qili.base.entity.CurrentUser;
import com.qili.controller.supervisor.SupervisorController;
import com.qili.core.annotation.Log;
import com.qili.core.utils.DictTypes;
import com.qili.core.utils.DictUtil;
import com.qili.core.utils.FileUtils;
import com.qili.entity.affaircase.dto.AffairCaseDTO;
import com.qili.entity.base.BaseCompany;
import com.qili.entity.base.BaseCompanyOwner;
import com.qili.entity.base.BaseDict;
import com.qili.entity.exam.ExExamExportModel;
import com.qili.entity.jc.JcProject;
import com.qili.entity.jc.dto.JcProjectDTO;
import com.qili.entity.supervisor.*;
import com.qili.entity.supervisor.dto.ProjectContractDTO;
import com.qili.entity.supervisor.dto.ProjectLeaderDTO;
import com.qili.entity.supervisor.dto.SupervisorProjectFromsDTO;
import com.qili.entity.supervisor.dto.*;
import com.qili.entity.supplier.SupplierProjectAccept;
import com.qili.entity.supplier.dto.ProjectPlaceDTO;
import com.qili.entity.supplier.dto.SupplierProjectDTO;
import com.qili.entity.sys.SysRegion;
import com.qili.entity.sys.SysUser;
import com.qili.entity.sys.dto.SysUserDTO;
import com.qili.entity.zx.*;
import com.qili.entity.zx.dto.*;
import com.qili.exception.MyException;
import com.qili.redis.RedisService;
import com.qili.service.SysUserService;
import com.qili.service.base.BaseCompanyOwnerService;
import com.qili.service.base.BaseCompanyService;
import com.qili.service.base.BaseDictService;
import com.qili.service.supervisor.*;
import com.qili.service.supplier.ProjectPlaceService;
import com.qili.service.supplier.SupplierProjectAcceptService;
import com.qili.service.supplier.SupplierProjectManagerService;
import com.qili.service.sys.SysRegionService;
import com.qili.service.zx.*;
import com.qili.util.*;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipOutputStream;

import static java.util.Objects.isNull;
@Controller
@Slf4j
@RequestMapping("/zx/projectManager")
public class ZxManagerController extends BaseController {

    @Autowired
    SupervisorFileService supervisorFileService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    SysRegionService sysRegionService;
    @Autowired
    BaseCompanyOwnerService baseCompanyOwnerService;
    @Autowired
    ZxProjectService zxProjectService;
    @Autowired
    ProjectContractService projectContractService;
    @Autowired
    ProjectLeaderService projectLeaderService;

    @Autowired
    ProjectAdminService  projectAdminService;

    @Autowired
    ZxProjectStageService zxProjectStageService;

    @Autowired
    ZxProjectMilepostService zxProjectMilepostService;

    @Autowired
    ZxProjectPayService zxProjectPayService;

    @Autowired
    ProjectPlaceService projectPlaceService;

    @Autowired
    UploadUtil uploadUtil;

    @Autowired
    SupervisorProjectFormsService supervisorProjectFormsService;
    @Autowired
    SupervisorProjectFormsDataService supervisorProjectFormsDataService;
    @Autowired
    ProjectSealRecordService projectSealRecordService;
    @Autowired
    ProjectBigEventService projectBigEventService;
    @Autowired
    ZxProjectModifiedRecordService modifiedRecordService;
    @Autowired
    ZxPayRecordService zxPayRecordService;
    @Autowired
    SupplierProjectManagerService supplierProjectManagerService;
    @Autowired
    BaseCompanyService baseCompanyService;
    @Autowired
    SupplierProjectAcceptService supplierProjectAcceptService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${supervisor.downloadPath}")
    private String uploadPath;
    @Value("${supervisor.tempPath}")
    private String tempPath;


    /**
     * 咨询服务首页
     *
     * @return
     */
    @GetMapping(value = "index")
    @RequiresPermissions("zx:index")
    public String index(HttpServletRequest request) {
        CurrentUser currentUser = CommonUtil.getUser();
        String userId = CommonUtil.getUserId();
        SysUser sysUser = sysUserService.selectByPrimaryKey(userId);
        if(sysUser==null){
            // 跳转到登陆页面
            request.setAttribute("type","login");
            return "/login";
        }
        // 个人中心设置的数量
        String tagnum = sysUser.getNumTag();
        currentUser.setNumTag(tagnum);
        String AsTags = currentUser.getTags();
        String[] AyTags;
        int count=0;
        if (StringUtil.isNotBlank(AsTags) && StringUtil.isNotBlank(tagnum)) {
            String[] newAyTags = new String[Integer.valueOf(tagnum)];
            AyTags = AsTags.split(";");
            String strname="";
            for (int k=0;k<AyTags.length;k++){
                String str= AyTags[k];
                String[] split = str.split(":");
                if(split!=null){
                    if(split.length>0){
                        String projectId= split[0];
                        if(StringUtil.isNotBlank(projectId)){
                            ZxProject project=zxProjectService.selectByPrimaryKey(projectId);
                            if(project!=null){
                                String status = project.getStatus();
                                if("000".equals(status)){
                                    //已经删除回收站的 清空session
                                    String projectName = project.getProjectName();
                                    strname=projectId+":"+projectName+";";
                                    AsTags=AsTags.replace(strname,"");
                                    count++;
                                }
                            }
                        }
                    }
                }
                sysUser.setTags(AsTags);
                sysUserService.updateTags(sysUser);
                currentUser.setTags(AsTags);
                Session session = com.qili.core.shiro.Principal.getSession();
                session.setAttribute("currentPrincipal", currentUser);
            }
            int length = AyTags.length;
            if (Integer.valueOf(tagnum) < length) {
                //清除多余的0
                for (int i = 0; i < length; i++) {
                    if (i < Integer.valueOf(tagnum)) {
                        newAyTags[i] = AyTags[i];
                    }
                }
                currentUser.setTags(StringUtils.join(newAyTags, ";") + ";");
            }
        }
        Session session = com.qili.core.shiro.Principal.getSession();
        session.setAttribute("currentPrincipal", currentUser);
        SupervisorFile supervisorFile = supervisorFileService.getPersonalImg(userId);
        request.setAttribute("file", supervisorFile);
        return "/zx/index";
    }

    /**
     *
     * @param temp
     * @return
     */
    @GetMapping(value = "isParamSys")
    @ResponseBody
    public String isParamSys(String temp){
        // 变量存的是 id:项目名称   d48e6b86cfd84a9aa6870694ff03c2df:撒打算打算
        String[] tempAsTags;
        if (StringUtil.isNotBlank(temp)){
            tempAsTags = temp.split(";");
            String strname="";
            for (int j = 0;j < tempAsTags.length;j++){
                String str= tempAsTags[j];
                String[] split = str.split(":");
                if(split != null && split.length > 0){
                    // 当前id
                    String projectId= split[0];
                    if(StringUtil.isNotBlank(projectId)){
                        ZxProject project=zxProjectService.selectByPrimaryKey(projectId);
                        if (project == null){
                            String projectName = split[1];
                            strname=projectId+":"+projectName+";";
                            temp = temp.replace(strname,"");
                        }
                    }
                }
            }
        }
        return temp;
    }

    /**
     * @Author:zhaoyongke
     * @Description: 管理项目首页
     * @Date:11:22 2021/6/25
     */
    @GetMapping(value = "projectIndex")
    @RequiresPermissions("zx:mgr")
    public String projectIndex(Model model, HttpServletRequest reques) {
        // 获取单位性质
        List<BaseDict> prostatus = DictUtil.getDictByType(DictTypes.UNIT_NATURE);

        List<BaseDict> hystatus = DictUtil.getDictByType(DictTypes.INDUSTRY);
        // 省
        List<SysRegion> provincelist = sysRegionService.selectListByLevelId("1");
        // 市
        List<SysRegion> citylist = sysRegionService.selectListByLevelId("2");
        /*项目类型*/
        List<BaseDict> projectTypeList = DictUtil.getDictByType(DictTypes.PROJECT_TYPEZX);
        //所属公司
        List<BaseCompanyOwner> ownerCompanyList = baseCompanyOwnerService.selectAll();
        model.addAttribute("ownerCompanyList", ownerCompanyList);
        model.addAttribute("projectTypeList", projectTypeList);
        model.addAttribute("provincelist", provincelist);
        model.addAttribute("citylist", citylist);
        model.addAttribute("prostatus", prostatus);
        model.addAttribute("hystatus", hystatus);
        // 查询 当前登录人  是不是 业主负责人和 单位管理员
        ProjectLeader  projectLeader=new ProjectLeader();
        projectLeader.setProjectLeader(CommonUtil.getUserId());
        List<ProjectLeader> select = projectLeaderService.select(projectLeader);
        if(select!=null){
            if(select.size()>0){
                model.addAttribute("yzzh", "1");
            }
        }

        ProjectAdmin  projectAdmin=new ProjectAdmin();
        projectAdmin.setUId(CommonUtil.getUserId());
        List<ProjectAdmin> selectadmin = projectAdminService.select(projectAdmin);
        if(selectadmin!=null){
            if(selectadmin.size()>0){
                model.addAttribute("yzzh", "1");
            }
        }

        return "/zx/projectManager/index";
    }

    /**
     * @param project
     * @param model
     * @param page
     * @param limit
     * @Author:Zhangshuo
     * @Description:项目管理----项目列表
     * @Date:9:47 2020-12-12
     */
    @ApiOperation(value = "/showProjectList", httpMethod = "GET", notes = "展示项目")
    @GetMapping(value = "showProjectList")
    @ResponseBody
    public ReType showProjectList(ZxProjectDTO project, Model model, String page, String limit) {
        // (1) 业主单位 （2） 承建单位  查询自己参与的项目
        //（3） 项目经理  查询自己创建的和自己参与的
        //（4） 监理工程师 （5）技术负责人 查询自己参与的项目
        //（6） 市场人员  发布的
        // (7) 管理员 公司高层 工程部经理 质控 查看全部
        // 2021 0708 添加咨询部门经理  查看全部
        //查询不是删除状态的项目
        project.setDestatus("000");
        project.setUserId(CommonUtil.getUserId());
        project.setField(humpToUnderline(project.getField()));
        //判断是否是管理员  公司高层  工程部经理  质控  :
        Subject subject = SecurityUtils.getSubject();
        if (subject.hasRole("admin") || subject.hasRole("gsgc") ||  subject.hasRole("zkjsry")  ) {
            project.setUserId(null);
        }
        // 正中总部的工程部经理可以查看正中总部的所有监理项目  分公司看到分公司的
        // 分公司总经理  看到自己公司的
        // 分公司工程部经理  只能看到自己的
        // 分公司咨询部门经理 只能看到自己的
        // 咨询部门经理   总部的
        if(subject.hasRole("fgszjl")  ||  subject.hasRole("gcbjl")  ||  subject.hasRole("fgsgcbjl") ||  subject.hasRole("fgsdeptcheckpersonzx") ||  subject.hasRole("deptcheckpersonzx")    ){
            // 分公司总经理  看到自己公司的
            SysUser sysUser = sysUserService.selectByPrimaryKey(CommonUtil.getUserId());
            // 公司Id
            String companyName = sysUser.getCompanyName();
            if(StringUtils.isBlank(companyName)){
                // 如果所所属公司为空  就不能显示出来信息
            }else{
                project.setUserId(null);
                project.setProjectOwner(companyName);
            }
        }
        return zxProjectService.show(project, Integer.valueOf(page), Integer.valueOf(limit));
    }

    //排序字段处理
    public static String humpToUnderline(String name) {
        StringBuilder result = new StringBuilder();
        if (name != null && name.length() > 0) {
            // 将第一个字符处理成大写
            result.append(name.substring(0, 1).toUpperCase());
            // 循环处理其余字符
            for (int i = 1; i < name.length(); i++) {
                String s = name.substring(i, i + 1);
                // 在大写字母前添加下划线
                if (s.equals(s.toUpperCase()) && !Character.isDigit(s.charAt(0))) {
                    result.append("_");
                }
                // 其他字符直接转成大写
                result.append(s.toUpperCase());
            }
        }
        return result.toString();
    }

    /**
     * @param
     * @Author:zhaoyongke
     * @Description:回收站
     * @Date:11:28 2021/6/25
     */
    @GetMapping(value = "viewHs")
    public String viewHs() {
        return "/zx/projectManager/viewHs";
    }

    /**
     * @param model
     * @param request
     * @Author:zhaoyongke
     * @Description: 账号管理
     * @Date:11:28 2021/6/25
     */
    @GetMapping(value = "viewAc")
    @RequiresPermissions("mgr:acczx")
    public String viewAc(Model model, HttpServletRequest request) {
        String projectId = request.getParameter("projectId");
        model.addAttribute("projectId", projectId);
        return "/zx/projectManager/viewAc";
    }

    /**
     * @param project
     * @param model
     * @param page
     * @param limit
     * @Author:zhaoyongke
     * @Description: 查询项目账号信息
     * @Date:22:26 2020/12/14
     */
    @GetMapping(value = "showProjectListAc")
    @ResponseBody
    public ReType showProjectListAc(ZxProjectDTO project, Model model, String page, String limit) {
        ReType re = new ReType();
        List<JSONObject> relist = new ArrayList<JSONObject>();
        String projectId = project.getProjectId();
        //查询业主管理员账号:
        List<SysUserDTO> sysUserDTOS = sysUserService.selectProjectAdmin(projectId);
        if (sysUserDTOS != null) {
            if(sysUserDTOS.size()>0){
                SysUserDTO admin = sysUserDTOS.get(0);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("realName", admin.getRealName());
                jsonObject.put("username", admin.getUsername());
                jsonObject.put("createBy", admin.getCreateBy());
                jsonObject.put("createDate", DateUtil.formatDate(admin.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                jsonObject.put("companyName", admin.getCompanyName());
                jsonObject.put("userId", admin.getId());
                jsonObject.put("userType", "业主单位管理员");
                relist.add(jsonObject);
                re.setData(relist);
            }

        } else {
            log.warn("没有查询到项目管理员账号");
        }
        // 查询业主单位
        ProjectLeaderDTO projectLeaderdto = new ProjectLeaderDTO();
        projectLeaderdto.setSupervisorProjectId(projectId);
        List<ProjectLeaderDTO> listleader = projectLeaderService.selectProjectLeaderList(projectLeaderdto);
        for (int i = 0; i < listleader.size(); i++) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("realName", listleader.get(i).getRealName());
            jsonObject.put("username", listleader.get(i).getUsername());
            jsonObject.put("createBy", listleader.get(i).getCreateBy());
            jsonObject.put("createDate", listleader.get(i).getCreateDate());
            jsonObject.put("companyName", listleader.get(i).getCompanyName());
            jsonObject.put("userId", listleader.get(i).getProjectLeader());
            jsonObject.put("userType", "业主单位");
            relist.add(jsonObject);
        }
        return re;
    }


    /*
     * 项目管理----回收站列表查询
     * */

    @ApiOperation(value = "/showProjectListHs", httpMethod = "GET", notes = "展示项目")
    @GetMapping(value = "showProjectListHs")
    @ResponseBody
    public ReType showProjectListHs(ZxProjectDTO project, HttpServletResponse response, Model model, String page, String limit) {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        // 查询已删除状态的项目 010
        project.setStatus("000");
        project.setUserId(CommonUtil.getUserId());
        //判断是否是管理员  公司高层  工程部经理  质控  :
        Subject subject = SecurityUtils.getSubject();
        if (subject.hasRole("admin")) {
            project.setUserId(null);
        }
        ReType re = zxProjectService.show(project, Integer.valueOf(page), Integer.valueOf(limit));
        return re;
    }


    /**
     * 项目管理----恢复回收站
     **/
    @ApiOperation(value = "/doHs", httpMethod = "POST", notes = "恢复回收站")
    @Log(desc = "恢复回收站", type = Log.LOG_TYPE.DEL)
    @PostMapping(value = "doHs")
    @ResponseBody
    public JsonUtil doHs(@RequestParam String ids) {
        JsonUtil re = new JsonUtil();
        if (StringUtils.isEmpty(ids)) {
            return JsonUtil.error("获取数据失败");
        }
        try {
            List<String> list = Tutil.split(ids);
            for (int i = 0; i < list.size(); i++) {
                String id = list.get(i);
                ZxProject project = zxProjectService.selectByPrimaryKey(id);
                /*恢复原来状态*/
                if (StringUtil.isNotBlank(project.getOldStatus())) {
                    project.setStatus(project.getOldStatus());
                } else {
                    project.setStatus("001");
                }
                zxProjectService.updateByPrimaryKey(project);
                re.setFlag(true);
                re.setMsg("操作成功");
            }
        } catch (Exception e) {
            re.setFlag(false);
            re.setMsg("操作失败：" + e.getMessage());
            e.printStackTrace();
        }
        return re;

    }


    /**
     * 项目管理----放到回收站
     **/
    @ApiOperation(value = "/deleteHs", httpMethod = "POST", notes = "放入回收站项目")
    @Log(desc = "放入回收站", type = Log.LOG_TYPE.DEL)
    @PostMapping(value = "deleteHs")
    @ResponseBody
    public JsonUtil deleteHs(@RequestParam String ids) {
        if (StringUtils.isEmpty(ids)) {
            return JsonUtil.error("获取数据失败");
        }
        JsonUtil re = new JsonUtil();
        try {
            List<String> list = Tutil.split(ids);
            for (int i = 0; i < list.size(); i++) {
                String id = list.get(i);
                ZxProject project = zxProjectService.selectByPrimaryKey(id);
                /*删除前保存原来的状态，还原后恢复原来状态*/
                project.setOldStatus(project.getStatus());
                project.setStatus("000");
                zxProjectService.updateByPrimaryKey(project);
                re.setFlag(true);
                re.setMsg("操作成功");
            }
        } catch (Exception e) {
            re.setMsg("擦作失败：" + e.getMessage());
            re.setFlag(false);
            e.printStackTrace();
        }
        return re;
    }

    @ApiOperation(value = "/resetPassword", httpMethod = "POST", notes = "重置密码")
    @Log(desc = "重置密码", type = Log.LOG_TYPE.DEL)
    @PostMapping(value = "resetPassword")
    @ResponseBody
    public JsonUtil resetPassword(SysUser sysUser) {
        JsonUtil re = new JsonUtil();
        try {
            String id = sysUser.getId();
            if (StringUtils.isEmpty(id)) {
                return JsonUtil.error("获取用户Id失败");
            }
            SysUser sysUserselect = sysUserService.selectByPrimaryKey(id);
            sysUserselect.setPassword("12345678");
            sysUserselect.setUpdateBy(CommonUtil.getUserId());
            sysUserselect.setUpdateDate(DateUtil.getCurrentDateTime());
            String pwd = Md5Util.getMD5(sysUserselect.getPassword().trim(), sysUserselect.getUsername().trim());
            sysUserselect.setPassword(pwd);
            sysUserService.updateByPrimaryKey(sysUserselect);
        } catch (Exception e) {
            re.setMsg(e.getMessage());
            re.setFlag(false);
            e.printStackTrace();
        }
        re.setFlag(true);
        re.setMsg("操作成功");
        return re;
    }


    /**
     * @param ids
     * @Author:Zhangshuo
     * @Description:删除回收站项目数据
     * @Date:20:23 2020-12-11
     */
    @ApiOperation(value = "/delprjfromrecycle", httpMethod = "POST", notes = "从回收站中删除项目")
    @Log(desc = "从回收站中删除项目", type = Log.LOG_TYPE.DEL)
    @PostMapping(value = "delprjfromrecycle")
    @ResponseBody
    public JsonUtil deleteProjects(@RequestParam String[] ids) {
        try {
            doDelete(ids);
            return JsonUtil.sucess("删除成功。");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("删除失败，" + e.getMessage());
        }
    }

    /**
     * @param ids
     * @Author:Zhangshuo
     * @Description:执行删除函数
     * @Date:21:38 2020-12-11
     */
    private void doDelete(String[] ids) {
        int AiFlag = zxProjectService.deleteProjectsFromRecycle(ids);
        if (AiFlag > 0) {
            // 修改流程无无效
            supervisorFileService.deleteAffairCaseByProjectIds(ids);
            //文件表
            supervisorFileService.deleteByProjectIds(ids);
            //表单表
//            supervisorProjectFormsService.deleteByProjectIds(ids);
//            // 分包数据
//            projectContractService.deleteByProjectIds(ids);
//            // 项目负责人
//            projectLeaderService.deleteByProjectIds(ids);
//            // 承建单位
//            projectUnitConstructionService.deleteByProjectIds(ids);
//            // 阶段数据
//            supervisorProjectStageService.deleteByProjectIds(ids);
//            // 里程数据
//            supervisorProjectMilepostService.deleteByProjectIds(ids);
//            // 付款方式
//            supervisorProjectPayService.deleteByProjectIds(ids);
            // 删除标签--用户
            deleteUserTag(ids);


        }
    }

    /**
     * @param ids
     * @Author:zhaoyongke
     * @Description:项目删除后清除 tags
     * @Date:14:32 2021/3/16
     */
    public void deleteUserTag(String[] ids) {
        CurrentUser currentUser = CommonUtil.getUser();
        for (int y = 0; y < ids.length; y++) {
            String proId = ids[y];
            Example ecj = new Example(SysUser.class);
            Example.Criteria ccj = ecj.createCriteria();
            ccj.andIsNotNull("tags");
            ccj.andLike("tags", "%" + proId + "%");
            List<SysUser> listuser = sysUserService.selectByExample(ecj);
            if (listuser.size() > 0) {
                for (int i = 0; i < listuser.size(); i++) {
                    SysUser user = listuser.get(i);
                    String AsTags = user.getTags();
                    if (StringUtil.isNotBlank(AsTags)) {
                        String[] ayTags = AsTags.split(";");
                        String strtag = "";
                        for (int t = 0; t < ayTags.length; t++) {
                            String tagstr = ayTags[t];
                            if (tagstr.indexOf(proId) > -1) {
                                strtag = tagstr + ";";
                                break;
                            }
                        }
                        if (StringUtil.isNotBlank(strtag)) {
                            String newstr = AsTags.replace(strtag, "");
                            user.setTags(newstr);
                            sysUserService.updateByPrimaryKey(user);
                            if (currentUser.getId().equals(user.getId())) {
                                currentUser.setTags(newstr);
                                Session session = com.qili.core.shiro.Principal.getSession();
                                session.setAttribute("currentPrincipal", currentUser);
                            }

                        }
                    }


                }

            }

        }

    }

    /**
     * @param
     * @Author:Zhangshuo
     * @Description:清除当前登录回收站
     * @Date:21:47 2020-12-11
     */
    @ApiOperation(value = "/delallprjfromrecycle", httpMethod = "POST", notes = "清除回收站中项目")
    @Log(desc = "清除回收站中项目", type = Log.LOG_TYPE.DEL)
    @PostMapping(value = "delallprjfromrecycle")
    @ResponseBody
    public JsonUtil deleteAllProjects() {
        JsonUtil jsonUtil = new JsonUtil();
        try {
            String AsUserId = CommonUtil.getUserId();
            if (StringUtil.isNotBlank(AsUserId)) {
                ZxProject supervisorproject = new ZxProject();
                supervisorproject.setCreateBy(AsUserId);
                supervisorproject.setStatus("000");
                List<ZxProject> AlstProjects = zxProjectService.select(supervisorproject);
                int AiCnt = AlstProjects.size();
                if (AiCnt == 0) {
                    return JsonUtil.error("没有需要删除的信息。");
                }
                String[] AyDelPrjIds = new String[AiCnt];
                for (int i = 0; i < AiCnt; i++) {
                    AyDelPrjIds[i] = AlstProjects.get(i).getId();
                }
                doDelete(AyDelPrjIds);
                jsonUtil.setFlag(true);
                jsonUtil.setMsg("删除成功");
                jsonUtil.setData(AyDelPrjIds);
                return jsonUtil;
            } else {
                return JsonUtil.error("用户验证失败。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("删除失败，" + e.getMessage());
        }
    }


    /**
     * @param request
     * @Author:zhaoyongke
     * @Description:項目管理----项目详情
     * @Date:13:22 2020/11/26
     * 三个权限 编辑，查看，显示
     */
    @GetMapping(value = "projectDetail")
    @RequiresPermissions(value={"mgr:editzx","mgr:viewzx","mgr:showzx"},logical= Logical.OR)
    public String projectDetail(HttpServletRequest request) {
        String type = request.getParameter("type");
        String id = request.getParameter("id");
        // 查询阶段表
        ZxProjectDTO zxProjectdto = getSupervisorProjectDTO(id);
/*        if ("m".equals(type)) {
            //编辑 项目结束后 收回承建单位权限
            Boolean iscj = projectUnitConstructionService.isCjUser(id);
            String status = zxProjectdto.getStatus();
            if ("003".equals(status)) {
                *//*项目结束状态*//*
                if (iscj) {
                    *//*承建单位*//*
                    request.setAttribute("message", "项目已经结束，您没有权限编辑！");
                    return "/error/lcerror";
                }
            }
        }*/
        //控制按钮
          bottonShow(request);
        /*判断是否是业主单位*/
//        Boolean isyz = projectLeaderService.isYzUser(id);
//        if (isyz) {
//            request.setAttribute("isyz", "1");
//        } else {
//            request.setAttribute("isyz", "0");
//        }
        // 查询业主单位
        ProjectLeaderDTO leaderdto = new ProjectLeaderDTO();
        leaderdto.setSupervisorProjectId(id);
        List<ProjectLeaderDTO> listyz = projectLeaderService.selectProjectLeaderList(leaderdto);
        // 查询项目阶段
        ZxProjectStageDTO dto = new ZxProjectStageDTO();
        dto.setProjectId(id);
        List<ZxProjectStageDTO> listStage = zxProjectStageService.selectProjectStage(dto);
        Boolean isProjectYc = false;
        ZxProjectMilepostDTO su = new ZxProjectMilepostDTO();
        su.setProjectId(id);
        List<ZxProjectMilepostDTO> AlistMilePost = zxProjectMilepostService.selectProjectmilepost(su);
        // 查询付款方式
        ZxProjectPayDTO payDTO = new ZxProjectPayDTO();
        payDTO.setSppPrjid(id);
        List<ZxProjectPayDTO> listpay = zxProjectPayService.selectSupervisorProjectPay(payDTO);

        ProjectPlaceDTO pacedto = new ProjectPlaceDTO();
        pacedto.setSupProjectId(zxProjectdto.getId());
        pacedto.setType("001");
        List<ProjectPlaceDTO> listpalce = projectPlaceService.selectPlace(pacedto);
        request.setAttribute("listpalce", listpalce);
        if("001".equals(zxProjectdto.getIsContinue())){
            zxProjectdto.setIsContinueName("是");
        }else{
            zxProjectdto.setIsContinueName("否");
        }
        request.setAttribute("project", zxProjectdto);
        request.setAttribute("listyz", listyz);// 业主单位
        request.setAttribute("listStage", listStage);// 项目阶段
        request.setAttribute("listmilepost", AlistMilePost);// 项目阶段
        /*request.setAttribute("listfb", listfb);// 项目分包if*/
        request.setAttribute("listpay", listpay);// 查询付款方式
        return "/zx/projectManager/projectdetail";
    }

    /**
     * @param request
     * @Author:zhaoyongke
     * @Description:控制按钮
     * @Date:12:23 2021/2/20
     */
    public void bottonShow(HttpServletRequest request) {
        //咨发两签
        Boolean jflq=sysUserService.isHasPermission("file:usecstampzx");
        if (jflq){
            request.setAttribute("jflq", "1");
        }
        //审批
        Boolean jlsp=sysUserService.isHasPermission("file:approvalzx");
        if (jlsp){
            request.setAttribute("jlsp", "1");
        }
        //审核
        Boolean jlsh=sysUserService.isHasPermission("file:checkzx");
        if (jlsh){
            request.setAttribute("jlsh", "1");
        }
        // 查看
        Boolean fview=sysUserService.isHasPermission("file:viewzx");
        if(fview){
            request.setAttribute("fview", "1");
        }
        // 导出
        Boolean fexport=sysUserService.isHasPermission("file:exportzx");
        if(fexport){
            request.setAttribute("fexport", "1");
        }
        //盖章
        Boolean fupseal=sysUserService.isHasPermission("file:stampzx");
        if(fupseal){
            request.setAttribute("fupseal", "1");
        }
        //签字
        Boolean fsign=sysUserService.isHasPermission("file:signzx");
        if(fsign){
            request.setAttribute("fsign", "1");
        }
        // 检查旁站  上传图片  确认上传 批量删除 插入图片
        Boolean fupimg=sysUserService.isHasPermission("file:upimg");
        if(fupimg){
            request.setAttribute("fupimg", "1");
        }
        Boolean filelistdel=sysUserService.isHasPermission("file:listdel");
        if(filelistdel){
            request.setAttribute("flistdel", "1");
        }
        Boolean filelistdept=sysUserService.isHasPermission("file:deptcheckzx");
        if(filelistdept){
            request.setAttribute("dept", "1");
        }



    }


    /**
     * @param spf_prjid
     * @Description:获取SupervisorProject
     * @Author:Zhangshuo
     * @Date:11:20 2020-12-19
     */
    private ZxProjectDTO getSupervisorProjectDTO(String spf_prjid) {
        ZxProjectDTO zxProjectdto = new ZxProjectDTO();
        //查询项目
        zxProjectdto.setId(spf_prjid);
        List<ZxProjectDTO> projectlist = zxProjectService.selectZxProject(zxProjectdto);

        if (projectlist.size() > 0) {
            String names = "";
            zxProjectdto = projectlist.get(0);
            String zxgcs = zxProjectdto.getZxAdviser();
            if (StringUtil.isNotBlank(zxgcs)) {
                String[] str = zxgcs.split(",");
                for (int x = 0; x < str.length; x++) {
                    SysUser sysUser = sysUserService.selectByPrimaryKey(str[x]);
                    if(sysUser!=null){
                        String name = sysUser.getRealName();
                        if (x == 0) {
                            names = name;
                        } else {
                            names = names + "," + name;
                        }
                    }

                }
                zxProjectdto.setZxAdviserName(names);
            }
        }
        return zxProjectdto;
    }

    /**
     * @param filedata
     * @param dto
     * @param request
     * @Author:zhaoyongke
     * @Description: 添加文件
     * @Date:10:51 2021/6/29
     */
    @RequestMapping(value = "/addFile", method = RequestMethod.POST)
    @ResponseBody
    public JsonUtil File(@RequestParam(value = "file", required = false) MultipartFile filedata, ZxProjectDTO dto, HttpServletRequest request) {

        JsonUtil re =new JsonUtil();
        String projectid = dto.getId();// 项目id
        String type = request.getParameter("type");//文件类型
        String lockkey = "zxwj_" +projectid+"_"+ type;
        String uuId = IdUtil.simpleUUID();
        try {
            lock(lockkey,uuId);
            JsonUtil  jsonUtil= ((ZxManagerController) AopContext.currentProxy()).addFile(filedata, dto, request);
            re.setFlag(jsonUtil.isFlag());
            re.setData(jsonUtil.getData());
            re.setMsg(jsonUtil.getMsg());
            re.setJosnObj(jsonUtil.getJosnObj());
            re.setStatus(jsonUtil.getStatus());
        }catch (Exception ex){
            re.setFlag(false);
            re.setMsg("文件上传异常，" + ex.getMessage());
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            System.out.println(ex.getMessage());
        }finally {
            unlock(lockkey,uuId);
            return re;
        }
    }

    public void lock(String key, String uuId) {
        int k = 0;
        for (; ; ) {

            System.out.println(redisService);
            boolean r = stringRedisTemplate.opsForValue().setIfAbsent(key, uuId);
            stringRedisTemplate.expire(key, 600, TimeUnit.SECONDS);

            if (r) {
                return;
            }
            if (k++ >= 1500) {
                throw new RuntimeException("lock error key = " + key);
            }
            int i = new Random().nextInt(30);
            try {
                TimeUnit.MILLISECONDS.sleep(300 + i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public void unlock(String key, String uuId) {
        if (uuId.equals(stringRedisTemplate.opsForValue().get(key))) {
            stringRedisTemplate.delete(key);
        }
    }
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public  JsonUtil addFile(MultipartFile filedata, ZxProjectDTO dto, HttpServletRequest request)throws Exception {
        //返回数据
        JsonUtil re = new JsonUtil();
        String uploadtype = dto.getUploadType();
        String userid = CommonUtil.getUserId(); // 当前用户信息
        String spmid = dto.getSpmId();// 里程id
        String stageId = dto.getStageId();//阶段id
        String fs_status = request.getParameter("fs_status");// 上传的时候 对应的状态p'r
        String projectid = dto.getId();// 项目id
        String fbId = request.getParameter("fbId");//分包表id
        String type = request.getParameter("type");//文件类型
        JSONObject jsonObject = new JSONObject();
        String filename = filedata.getOriginalFilename();
        try {
//            String role = sysUserService.getUserRole(projectid);
//            if ("xmjl".equals(role) || "cj".equals(role)) {
//                if ("cj".equals(role)) {
//                    BaseDict wjdict = DictUtil.getDictByCode(DictTypes.WJ, type);
//                    String level11 = wjdict.getBadtLevel11();
//                    if (level11.indexOf("cj") < 0) {
//                        re.setMsg("您没有权限上传文档");
//                        re.setFlag(false);
//                        return re;
//                    }
//                }
//
//            } else {
//                re.setMsg("您没有权限上传文档");
//                re.setFlag(false);
//                return re;
//            }

            /*项目大事记*/
            projectBigEventService.saveProejctBigEventZx(projectid, spmid, stageId);
            //对文件中图片和文件的名称做处理
            JsonUtil error = doSomeSpecialThings(dto, uploadtype);
//            if (error != null) {
//                re.setFlag(false);
//                re.setMsg(error.getMsg());
//                return error;
//            }
            if ((StringUtil.isBlank(uploadtype)) || (!uploadtype.equals("002"))) {
                //更新阶段和里程状态
                updateStageAndMilePostStatus(spmid, stageId, fs_status, jsonObject, type, fbId);
            }
            //上传文件以及保存数据
            savedoUploadAndSaveFile(filedata, dto, uploadtype, userid, spmid, stageId, projectid, fbId, jsonObject, filename);

            if (jsonObject.get("wj_status") == null) {
                jsonObject.put("wj_status", "");
            }
            if (jsonObject.get("lc_status") == null) {
                jsonObject.put("lc_status", "");
            }
            if (jsonObject.get("jd_status") == null) {
                jsonObject.put("jd_status", "");
            }
            re.setData(jsonObject);
            re.setFlag(true);
            return re;
        } catch (Exception e) {
            e.printStackTrace();
            re.setFlag(false);
            re.setMsg("文件上传异常，" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            System.out.println(e.getMessage());
        } finally {
            return re;
        }
    }

    /**
     * @param dto
     * @param uploadtype
     * @Description:
     * @Author:Zhangshuo
     * @Date:21:48 2020-12-20
     */
    private JsonUtil doSomeSpecialThings(ZxProjectDTO dto, String uploadtype) {
        String AsType = dto.getType();
        //002 上传图片方式
        if ("002".equals(uploadtype) && !"093".equals(AsType) && !"040".equals(AsType)) {
            if ("020".equals(AsType) ) {
                //承建付款申请 和 监理付款申请 不包含部位
                String positonName = dto.getPositionName();
                dto.setPositionName("第" + positonName + "次");
            } else {
                if (StringUtil.isBlank(dto.getPositionName())) {
                    return JsonUtil.error("部位不允许为空！！");
                } else {
                    // 部位为汉字
                    String reg = "[\\u4e00-\\u9fa5]+";
                    boolean result = dto.getPositionName().matches(reg);
                    if (!result) {
                        return JsonUtil.error("部位请填写汉字！！");
                    }
                }
            }
        }
        return null;
    }
    /**
     * @param spmid
     * @param stageId
     * @param fs_status
     * @param jsonObject
     * @Description:更新阶段和里程状态
     * @Author:Zhangshuo
     * @Date:22:31 2020-12-18
     */
    private void updateStageAndMilePostStatus(String spmid, String stageId, String fs_status, JSONObject jsonObject, String type, String fbId) {
        // 里程
        ZxProjectMilepost supervisorProjectMilepost = zxProjectMilepostService.selectByPrimaryKey(spmid);
        // 阶段
        ZxProjectStage stage = zxProjectStageService.selectByPrimaryKey(stageId);
        String stepNum = supervisorProjectMilepost.getStepNum();
        // 里程本身的状态
        String finishStatus = supervisorProjectMilepost.getFinishStatus();
        String[] ayStatus = stepNum.split(",");
        String asPostStartIdx = fs_status.substring(0, 1);// 例如  10  20  截取  为  1 , 2
        String strsatus = ayStatus[Integer.valueOf(asPostStartIdx) - 1];
        // 该里程的状态为 进行中  或未开始 或 本文件类型为未开始的状态
        if (strsatus.substring(1, 2).equals("0") && ("0".equals(finishStatus) || "1".equals(finishStatus) || "3".equals(finishStatus))) {// 判断当前文件类型的状态
            ayStatus[Integer.valueOf(asPostStartIdx) - 1] = fs_status;// 更新文件类型状态
            String str = Arrays.toString(ayStatus).replace("[", "").replace("]", "").replace(" ", "");
            supervisorProjectMilepost.setStepNum(str);
            // 更新状态字符串
            zxProjectMilepostService.updateByPrimaryKey(supervisorProjectMilepost);
            jsonObject.put("wj_status", "1");
        }

        if ("0".equals(finishStatus)) {
            supervisorProjectMilepost.setFinishStatus("1");//进行中
            zxProjectMilepostService.updateByPrimaryKey(supervisorProjectMilepost);
            jsonObject.put("lc_status", "1");// 里程进行中
        }
        if ("0".equals(stage.getFinishStatus())) {
            stage.setFinishStatus("1");//进行中
            zxProjectStageService.updateByPrimaryKey(stage);
            jsonObject.put("jd_status", "1");// 阶段
        }
    }

    /**
     * @param filedata
     * @param dto
     * @param uploadtype
     * @param userid
     * @param spmid
     * @param stageId
     * @param projectid
     * @param fbId
     * @param jsonObject
     * @param filename
     * @Description: 上传文件已经保存到数据库中
     * @Author:Zhangshuo
     * @Date:21:51 2020-12-20
     */
    private void savedoUploadAndSaveFile(MultipartFile filedata, ZxProjectDTO dto, String uploadtype, String userid, String spmid, String stageId, String projectid, String fbId, JSONObject jsonObject, String filename) throws Exception {
        //上传文件
        String AsFileStuffix = FilePathUtil.getFileSufiix(filename);
        /*检验文件格式*/
        updatejyFileType(AsFileStuffix, dto.getType());
        /*校验文件名称*/
        updatejyFileName(filename, dto.getType());

        UploadType uploadType = getFileUploadType(dto, spmid, projectid, fbId, AsFileStuffix, uploadtype);

        BaseDict wjdict = DictUtil.getDictByCode(DictTypes.WJZX, dto.getType());
        String badtLevel14 = wjdict.getBadtLevel14();
        if("1".equals(badtLevel14)){
            // 这些文件 不需要系统生成文件名称
            uploadType.setFileName(filename);
        }
        LoadType loadType = uploadUtil.upload(filedata, uploadType);

        if("1".equals(badtLevel14)){
            //判断上传的文件是否重复
            SupervisorFile  supervisorFile=new SupervisorFile();
            File currentFile = loadType.getCurrentFile();
            String path = currentFile.getPath();
            supervisorFile.setUrl(path);
            int i = supervisorFileService.selectCount(supervisorFile);
            if(i>0){
                throw   new Exception("存在同名文件，请修改文件名后再上传！");
            }

        }
        //文件名称
        String AsNewFileName = uploadType.getFileName();
        //保存文件表
        SupervisorFile filedto = saveSupervisorFile(dto, userid, spmid, stageId, projectid, fbId, loadType, AsNewFileName, uploadType.getInd());
        //  20220627  增加第一次上传文件的时间  和 更新最后一次上传时间
        ZxProject  project=zxProjectService.selectByPrimaryKey(projectid);
        if(StringUtils.isBlank(project.getUploadBeginTime())){
            project.setUploadBeginTime(DateUtil.getCurrentDateString());
        }
        project.setUploadLastTime(DateUtil.getCurrentDateString());
        zxProjectService.updateByPrimaryKey(project);


        //解析文件数据
//        HashMap map = saveparsingFileData(loadType.getFilePath(), dto, fbId);
        /*reson 变更处理表更原因*/
//        jsonObject.put("bgreason", map.get("reason"));
        jsonObject.put("id", filedto.getId());
        jsonObject.put("filename", AsNewFileName);
    }

    /**
     * @param AsFileStuffix
     * @param type
     * @Author:zhaoyongke
     * @Description:校验文件类型 是否和字典中的值一致
     * @Date:16:51 2021/1/12
     */
    public void updatejyFileType(String AsFileStuffix, String type) throws Exception {
        BaseDict wjdict = DictUtil.getDictByCode(DictTypes.WJZX, type);
        Boolean isTrue = false;
        /*文件类型是否正确判断*/
        String dicwjtype = wjdict.getBadtLevel6();
        if (StringUtil.isNotBlank(dicwjtype)) {
            String[] dictypesz = dicwjtype.split(",");
            if (dictypesz.length > 0) {
                for (int i = 0; i < dictypesz.length; i++) {
                    String wjtype = dictypesz[i].toLowerCase();
                    String stuffix = AsFileStuffix.toLowerCase() + "";
                    if (stuffix.indexOf(wjtype) != -1) {
                        isTrue = true;
                        break;
                    }
                }
            } else {
                isTrue = true;
            }
        } else {
            isTrue = true;
        }
        if (!isTrue) {
            throw new Exception("正确的文件格式为：" + dicwjtype);
        }
    }

    /**
     * @param fileName
     * @param type
     * @Author:zhaoyongke
     * @Description: 校验文件名称
     * @Date:17:20 2021/1/12
     */
    public void updatejyFileName(String fileName, String type) throws Exception {
        BaseDict wjdict = DictUtil.getDictByCode(DictTypes.WJ, type);
        String isjy = wjdict.getBadtLevel7();
        String dictFileName = wjdict.getBadtName();
        if ("1".equals(isjy)) {
            if (fileName.indexOf(dictFileName) == -1) {
                throw new Exception("您上传的文件名称中必须包含：" + dictFileName);
            }
        }
    }

    /**
     * @param dto
     * @param spmid     里程ID
     * @param projectid 项目ID
     * @param fbId      分包ID
     * @Author:Zhangshuo
     * @Description:
     * @Date:12:34 2020/12/4
     */
    private UploadType getFileUploadType(ZxProjectDTO dto, String spmid, String projectid, String fbId, String psFileStuffix, String pUploadType) throws Exception {
        ZxProject AoSupervisorProject = zxProjectService.selectByPrimaryKey(projectid);
        String AsType = dto.getType();
        ProjectContract AoPackage = new ProjectContract();
        if (null != fbId && !"".equals(fbId)) {
            AoPackage = projectContractService.selectByPrimaryKey(fbId);
        }
        String AsFbCode = AoPackage.getCode();
        BaseDict AoBaseDict = DictUtil.getDictByCode(DictTypes.WJZX, AsType + (StringUtil.isBlank(pUploadType) ? "" : pUploadType));
        String AsFpId = AoBaseDict.getBadtLevel2();

        if (StringUtil.isNotBlank(AsFpId)) {
            SupervisorFile AoSupervisorFile = new SupervisorFile();
            //  咨询款支付申请
            if (("020".equals(AsType) ) && ("002".equals(pUploadType))) {
                /*附件通过parentId查询*/
                AoSupervisorFile.setParentId(dto.getParentId());
            } else {
                AoSupervisorFile.setProjectId(projectid);
                AoSupervisorFile.setSpmId(spmid);
                AoSupervisorFile.setPcId(fbId);
                AoSupervisorFile.setType(AsType);
            }
            UploadType uploadType = prepareFileUploadType(AoSupervisorProject, AsType, AsFbCode, AsFpId, psFileStuffix, dto.getFileCount(), AoSupervisorFile, pUploadType, dto.getPositionName());
            return uploadType;
        } else {
            throw new Exception("文件类型：" + AsType + "，未发现配置存储路径，请到数据字典中配置。");
        }
    }
    /**
     * @param
     * @Author:Zhangshuo
     * @Description:
     * @Date:10:51 2020/12/4
     */
    private UploadType prepareFileUploadType(ZxProject poSupervisorProject, String psFileType, String psFbCode, String psFpId, String psFileStuffix, int piFileCount, SupervisorFile poSupervisorFile, String pUploadType, String pPositionName) {
        return prepareUploadType(0, poSupervisorProject.getProjectName(), psFileType, psFbCode, psFpId, psFileStuffix, piFileCount, poSupervisorFile, pUploadType, pPositionName);
    }

    /**
     * @param type             上传类型 UploadType EnumByType
     * @param psPrjName        项目名称
     * @param psFileType       文件类型
     * @param psFbCode         分包编号
     * @param psFpId           路径配置表ID
     * @param poSupervisorFile
     * @Author:Zhangshuo
     * @Description:获取上传UploadType
     * @Date:10:03 2020/12/4
     */
    public UploadType prepareUploadType(int type, String psPrjName, String psFileType, String psFbCode, String psFpId, String psFileStuffix, int piFileCount, SupervisorFile poSupervisorFile, String pUploadType, String pPositionName) {
        // 获取文件名称
        String AsFileName = FileUtils.getFileNameZx(psPrjName, psFileType, psFbCode, psFileStuffix, piFileCount, poSupervisorFile, pUploadType, pPositionName);
        // 替换项目名称
        ArrayList<String> placeHolder = new ArrayList<String>();
        placeHolder.add(psPrjName);
        placeHolder.add(psFbCode);
        placeHolder.add(pPositionName);
        UploadType uploadType = UploadType.getEnumByType(type);
        uploadType.setFileName(AsFileName);
        uploadType.setFilePathId(psFpId);
        uploadType.setPlaceholder(placeHolder);
        uploadType.setInd(poSupervisorFile.getInd());
        return uploadType;
    }

    /**
     * @param dto
     * @param userid
     * @param spmid
     * @param stageId
     * @param projectid
     * @param fbId
     * @param loadType
     * @param asNewFileName
     * @Author:Zhangshuo
     * @Description:保存数据到文件表
     * @Date:22:21 2020-12-08
     */
    private SupervisorFile saveSupervisorFile(ZxProjectDTO dto, String userid, String spmid, String stageId, String projectid, String fbId, LoadType loadType, String asNewFileName, Integer ind) {
        SupervisorFile filedto = new SupervisorFile();
        filedto.setFileName(asNewFileName);
        filedto.setFileType(loadType.getSuffix());
        filedto.setType(dto.getType());
        filedto.setCreateBy(userid);
        filedto.setCreateDate(new Date());
        filedto.setUrl(loadType.getFilePath());
        filedto.setInd(ind);
        if (null != fbId && !"".equals(fbId)) {
            filedto.setPcId(fbId);// 分包id
        }
        filedto.setParentId(dto.getParentId());
        filedto.setPositionName(dto.getPositionName());
        filedto.setProjectId(projectid);// 项目id
        filedto.setSpmId(spmid);// 里程id
        filedto.setStageId(stageId);// 阶段id
        supervisorFileService.insert(filedto);
        supervisorFileService.setFilePathDics(filedto);
        // 解析文件  保存文本用于 智能检索
        try {
            supervisorFileService.parseFileToText(filedto);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return filedto;
    }


    /**
     * @param ids
     * @Author:zhaoyongke
     * @Description:删除附件
     * @Date:14:55 2020/11/20
     */
    @RequestMapping(value = "/deleteFile", method = RequestMethod.POST)
    @ResponseBody
    public JsonUtil deleteFile(String ids,String type) {
        List<String> list = Tutil.split(ids);
        JsonUtil re = new JsonUtil();
        try {
            for (int i = 0; i < list.size(); i++) {
                SupervisorFile fileselect = new SupervisorFile();
                fileselect.setId(list.get(i));
                List<SupervisorFile> fileselectlist = supervisorFileService.select(fileselect);
                //文件类型
                String wjcode = fileselectlist.get(0).getType();
                String createType = fileselectlist.get(0).getCreateType();
                if("1".equals(createType)){
                    re.setMsg("从供需移动过来的文件，不允许删除!");
                    re.setFlag(false);
                    return re;
                }
//                /*获取该文件的流程状态*/
                Boolean lcstatus = getLcStatus(fileselectlist, wjcode, "001");
                if (!lcstatus) {
                    re.setMsg("流程进行中，不允许删除!");
                    re.setFlag(false);
                    return re;
                }
                SupervisorFile deletefile = supervisorFileService.selectByPrimaryKey(list.get(i));
                String deletePrId = deletefile.getProjectId();
                String role = sysUserService.getUserRoleZx(deletePrId);
                if ("xmjl".equals(role) || "zxdwhyfzr".equals(role)  || "zxgw".equals(role)) {
                    if ("zxgw".equals(role)) {
                        /*承建单位*/
                        String uplaodUser = deletefile.getCreateBy();
                        //如果该文件不是自己上传的
                        if (!CommonUtil.getUserId().equals(uplaodUser)) {
                            re.setMsg("您没有权限操作!");
                            re.setFlag(false);
                            return re;
                        }

                    }

                } else {
                    re.setMsg("您没有权限操作!");
                    re.setFlag(false);
                    return re;
                }

                supervisorFileService.deleteByPrimaryKey(list.get(i));
                //查询子文件
                SupervisorFile file = new SupervisorFile();
                file.setParentId(list.get(i));
                List<SupervisorFile> filelist = supervisorFileService.select(file);
                for (int y = 0; y < filelist.size(); y++) {
                    String zfileId = filelist.get(y).getId();
                    supervisorFileService.deleteByPrimaryKey(zfileId);
                }


            }
            re.setMsg("删除成功");
            re.setFlag(true);
        } catch (
                Exception e) {
            re.setMsg("删除失败!" + e.getMessage());
            re.setFlag(false);
            e.printStackTrace();
        }
        return re;
    }
    /**
     * @param filelist
     * @param wjcode
     * @Author:zhaoyongke
     * @Description: 判断流程是否结束
     * @Date:14:55 2020/12/31
     */
    public Boolean getLcStatus(List<SupervisorFile> filelist, String wjcode, String type) {
        BaseDict dict = DictUtil.getDictByCode(DictTypes.WJZX, wjcode);
        String lcsl = dict.getBadtLevel3();
        Boolean isxs = true;
        if (StringUtil.isNotBlank(lcsl)) {
            // 流程都结束后才可以显示
            //流程状态0 内部未发起流程1 内部进行中 2 内部流程审核通过3内部流程审核不通过4外部流程进行中5外部流程审核通过（归档）6 外部流程审核不通过
            for (int i = 0; i < filelist.size(); i++) {
                SupervisorFile file = filelist.get(i);
                //流程状态
                String lcstatus = file.getLcStatus();
                // 3 包含外部流和内部流程 2 只包含外部流程   1 只包含内部流程
                if ("3".equals(lcsl) || "2".equals(lcsl)) {
                    if ("001".equals(type)) {
                        //  20210821 驳回后可以删除  内部驳回后的状态为 0
                        if("3".equals(lcsl)){
                            if("0".equals(lcstatus)){
                                isxs = true;// 内部流程驳回可以删除
                                break;
                            }
                        }else if("2".equals(lcsl)){
                            if("2".equals(lcstatus)){
                                isxs = true;// 外部流程驳回可以删除
                                break;
                            }

                        }
                        if (!"3".equals(lcstatus) && !"5".equals(lcstatus) && !"6".equals(lcstatus) && lcstatus != null && !"".equals(lcstatus)) {
                            // 流程进行 不能删除
                            isxs = false;
                            break;
                        }
                    } else {
                        // 20210810 修改为 外部流程任何状态下都可以点击完成 ，内部流程 必须走完才能点击完成

                        String projectId = file.getProjectId();
                        String role = sysUserService.getUserRole(projectId);
//                        if ("zjlgcs".equals(role)) {
//                            isxs = true;
//                            break;
//                        }
                        if ("2".equals(lcsl)) {
                            isxs = true;
                            break;
                            // 外部流程 不需要判断流程状态就可以点击完成
                        } else if ("3".equals(lcsl)) {
                            // 包含内外部流程的 只要内部流程审核通过就可以点击完成

                            if (StringUtil.isBlank(lcstatus) || "0".equals(lcstatus) || "1".equals(lcstatus) || "3".equals(lcstatus)) {
                                isxs = false;
                                break;
                            }
                        }
//                        if (!"5".equals(lcstatus)) {
//                            // 流程未结束  不能点击完成按钮 按钮 隐藏
//                            isxs = false;
//                            if("4".equals(lcstatus) ){
//                                //流程进行中,判断该操作人是不是项目的总监理工程师:
//                                String actor = CommonUtil.getUserId();
//                                String projectId = file.getProjectId();
//                                if(StringUtils.isNotBlank(projectId)){
//                                    SupervisorProject project = supervisorProjectService.selectByPrimaryKey(projectId);
//                                    if(null != project){
//                                        //项目的总监理工程师:
//                                        String supervisorEngineer = project.getSupervisorEngineer();
//                                        if(actor.equals(supervisorEngineer)){
//                                            isxs = true;
//                                        }
//                                    }
//                                }
//                            }
//                            break;
//                        }
                    }

                } else if ("1".equals(lcsl)) {
                    if ("001".equals(type)) {
                        if("0".equals(lcstatus)){
                            isxs = true;// 内部流程驳回可以删除
                            break;
                        }
                        if (!"2".equals(lcstatus) && !"3".equals(lcstatus) && lcstatus != null && !"".equals(lcstatus)) {
                            // 流程进行 不能删除
                            isxs = false;
                            break;
                        }
                    } else {
                        String projectId = file.getProjectId();
                        String role = sysUserService.getUserRole(projectId);
//                        if ("zjlgcs".equals(role)) {
//                            isxs = true;
//                            break;
//                        }
                        if (!"2".equals(lcstatus)) {
                            // 流程未结束  不能点击完成按钮 按钮 隐藏
                            isxs = false;
                            break;
                        }
                    }

                }

            }
        }
        return isxs;
    }




    /**
     * @param supervisorProjectFromsDTO
     * @Author:zhaoyongke
     * @Description: 表单保存文件
     * @Date:13:06 2020/11/30
     */
    @RequestMapping(value = "/addFormFile", method = RequestMethod.POST)
    @ResponseBody
    public JsonUtil addFormFile(SupervisorProjectFromsDTO supervisorProjectFromsDTO) {
        JsonUtil re = new JsonUtil();
        JSONObject jsonObject = new JSONObject();
        //交付记录单介质类型复选处理
        ArrayList<SupervisorProjectFormsData> formData=supervisorProjectFromsDTO.getFormDataList();
        if(formData!=null&&formData.size()>0&&formData.get(0).getChecks()!=null&&formData.get(0).getChecks().size()>0){
            for(int i=0;i<formData.size();i++){
                StringJoiner check=new StringJoiner(",");
                ArrayList<String> checks=formData.get(i).getChecks();
                if(checks!=null&&checks.size()>0){
                    for (int j = 0; j < checks.size(); j++) {
                        if(StringUtil.isNotBlank(checks.get(j))) {
                            check.add(checks.get(j));
                        }
                    }
                }
                formData.get(i).setData2(check.toString());
            }
        }
        try {
            //文件保存路径
            String AsFilePath = prepareFormSavePath(-1, supervisorProjectFromsDTO);

            //判断咨询已支付金额小于等于咨询合同额
            ZxProject zxProject = new ZxProject();
            zxProject.setId(supervisorProjectFromsDTO.getSpfPrjid());
            //查询项目信息
            zxProject = zxProjectService.selectOne(zxProject);
            //已支付金额
            String jlPayMoney=supervisorProjectFromsDTO.getSpfF41();
            //合同额
            String htMoney=zxProject.getHtMoney();
            //判断项目中已支付额是否有值
            ZxProjectMilepost zxpm= zxProjectMilepostService.selectByPrimaryKey(supervisorProjectFromsDTO.getSpfMilid());
            if("015".equals(zxpm.getMilepostNo())) {
                if (zxProject.getJlPayMoney() == null || "".equals(zxProject.getJlPayMoney())) {
                    int flag = 0;
                    if (StringUtil.isNotBlank(jlPayMoney)) {
                        flag = new BigDecimal(htMoney).compareTo(new BigDecimal(jlPayMoney));
                    }
                    if (flag < 0) {
                        re.setFlag(false);
                        re.setMsg("已支付金额不可以比合同额大！");
                        return re;
                    }
                } else {
                    //取出原值累加
                    BigDecimal num = new BigDecimal(zxProject.getJlPayMoney()).add(new BigDecimal(supervisorProjectFromsDTO.getSpfF41()));
                    int flag = new BigDecimal(htMoney).compareTo(num);
                    if (flag < 0) {
                        re.setFlag(false);
                        re.setMsg("已支付金额不可以比合同额大！");
                        return re;
                    }
                }
            }
            //获取Form实例
            SupervisorProjectForms AoForms = getSupervisorProjectForms(supervisorProjectFromsDTO, AsFilePath);
            supervisorProjectFormsService.insertSelective(AoForms);
            //针对个别表格数据  把表格数据保存到 form-data 表中 比如 加电检验记录表
            ArrayList<SupervisorProjectFormsData> AlstFormData = supervisorProjectFromsDTO.getFormDataList();
            if (!isNull(AlstFormData)) {
                addFormData(AlstFormData, AoForms.getSpfId());
            }
            re.setFlag(true);
            re.setMsg("操作成功");
            //FormID
            jsonObject.put("spfId", AoForms.getSpfId());
            //PatchConfig ID
            jsonObject.put("fpid", supervisorProjectFromsDTO.getBfcId());
            re.setData(jsonObject);
        } catch (Exception e) {
            re.setMsg("操作失败" + e.getMessage());
            re.setFlag(false);
            e.printStackTrace();
        }
        return re;
    }
    /**
     * @Author:zhaoyongke
     * @Description: 针对表单存在表格得情况  插入 form-data
     * @Date:11:55 2020/12/5
     */
    public void addFormData(List<SupervisorProjectFormsData> plstFormData, String formid) {
        for (int i = 0; i < plstFormData.size(); i++) {
            SupervisorProjectFormsData formsData = plstFormData.get(i);
            formsData.setSpfId(formid);
            supervisorProjectFormsDataService.insertSelective(formsData);
        }
    }

    /**
     * @param poSupervisorProjectFromsDTO
     * @Author:Zhangshuo
     * @Description:
     * @Date:10:29 2020/12/4
     */
    private String prepareFormSavePath(int piFileCount, SupervisorProjectFromsDTO poSupervisorProjectFromsDTO) {
        // 准备上传参数
        String AsPrjName = poSupervisorProjectFromsDTO.getProjectName();
        String AsFileType = poSupervisorProjectFromsDTO.getSpfFilecode();
        String AsFbCode = poSupervisorProjectFromsDTO.getFbCode();
        String AsFpId = poSupervisorProjectFromsDTO.getBfcId();
        SupervisorFile AoSupervisorFile = getSupervisorFile(poSupervisorProjectFromsDTO);
        AoSupervisorFile.setType(AsFileType);

        String AsFileStuffix = ".doc";
        UploadType uploadType = prepareUploadType(0, AsPrjName, AsFileType, AsFbCode, AsFpId, AsFileStuffix, piFileCount, AoSupervisorFile, "", "");
        poSupervisorProjectFromsDTO.setFileInd(uploadType.getInd());
        String AsFilePath = FilePathUtil.getFullSavePathAndNameByConfigFileId(uploadType);
        return AsFilePath;
    }

    /**
     * @param supervisorProjectFromsDTO
     * @param psFilePath
     * @Author:Zhangshuo
     * @Description:
     * @Date:10:20 2020/12/4
     */
    private SupervisorProjectForms getSupervisorProjectForms(SupervisorProjectFromsDTO supervisorProjectFromsDTO, String psFilePath) {
        SupervisorProjectForms form = new SupervisorProjectForms();
        BeanUtil.copyNotNullBean(supervisorProjectFromsDTO, form);
        form.setSaveFilePath(psFilePath);
        form.setSpfId(IdUtil.simpleUUID());
        return form;
    }

    /**
     * @param poSupervisorProjectFromsDTO
     * @Author:Zhangshuo
     * @Description:
     * @Date:9:31 2020/12/4
     */
    private SupervisorFile getSupervisorFile(SupervisorProjectFromsDTO poSupervisorProjectFromsDTO) {
        SupervisorFile file = new SupervisorFile();
        file.setProjectId(poSupervisorProjectFromsDTO.getSpfPrjid());
        file.setStageId(poSupervisorProjectFromsDTO.getSpfStaid());
        file.setSpmId(poSupervisorProjectFromsDTO.getSpfMilid());
        if (StringUtil.isNotBlank(poSupervisorProjectFromsDTO.getPcId())) {
            file.setPcId(poSupervisorProjectFromsDTO.getPcId());
        }
        return file;
    }

    /**
     * @param
     * @Author:zhaoyongke
     * @Description: 点击完成按钮 擦作
     * @Date:9:57 2020/11/7
     */
    @RequestMapping(value = "/updateFinish", method = RequestMethod.POST)
    @ResponseBody
    public JsonUtil updateFinish(HttpServletRequest request) {
        JsonUtil re = new JsonUtil();
        try {
            JSONObject jsonObject = new JSONObject();
            //项目id:
            String projectId = request.getParameter("id");
            // 完成类型 002 代表到货验收需要每个分包完成的情况
            String finshType = request.getParameter("finshType");
            // 完成第几步
            String fs_status = request.getParameter("fs_status");
            // 里程id
            String spm_Id = request.getParameter("spmId");
            // 阶段id
            String stageId = request.getParameter("stageId");
            String fileType = request.getParameter("fileType");
            //普通形式获取上传文件类型
            String fileTypePt = request.getParameter("fileTypePt");
            ZxProjectStage stagef = zxProjectStageService.selectByPrimaryKey(stageId);
            // 文件类型数量
            Integer typeNum = 0;
            if (request.getParameter("typeNum") != null) {
                typeNum = Integer.valueOf(request.getParameter("typeNum"));
            }


                /*非到货验收状态处理*/
                String restr = updateFinishSt(re, fileTypePt, fileType, jsonObject, fs_status, typeNum, projectId, stageId, spm_Id, stagef, request);
                if (StringUtil.isNotBlank(restr)) {
                    return JsonUtil.error(restr);
                }

            updateAfFinish(projectId, stageId, jsonObject);
            if (jsonObject.get("fb_status") == null) {
                jsonObject.put("fb_status", "");
            }
            if (jsonObject.get("lc_status") == null) {
                jsonObject.put("lc_status", "");
            }
            if (jsonObject.get("jd_status") == null) {
                jsonObject.put("jd_status", "");
            }
            re.setData(jsonObject);
            re.setMsg("操作成功");
            re.setFlag(true);
        } catch (
                Exception e) {
            re.setMsg("操作失败！！" + e.getMessage());
            re.setFlag(false);
            e.printStackTrace();
        }
        return re;
    }

    /**
     * @param projectId
     * @param stageId
     * @param object
     * @Author:zhaoyongke
     * @Description:延期的阶段和项目 恢复原来状态
     * @Date:18:41 2021/3/5
     */
    public void updateAfFinish(String projectId, String stageId, JSONObject object) {
        ZxProjectStage stage = zxProjectStageService.selectByPrimaryKey(stageId);
        String stageStatus = stage.getFinishStatus();
        if ("3".equals(stageStatus)) {
            ZxProjectMilepost milepostYc = new ZxProjectMilepost();
            milepostYc.setProjectId(projectId);
            milepostYc.setSupervisorProjectStageId(stageId);
            milepostYc.setFinishStatus("3");
            int countlc = zxProjectMilepostService.selectCount(milepostYc);
            if (countlc == 0) {
                // 没有延期的里程 修改回原状态(不会是 0 2 )
                stage.setFinishStatus("1");
                object.put("jd_status", "1");
                zxProjectStageService.updateByPrimaryKey(stage);
            }
        }


        ZxProject projectselect = zxProjectService.selectByPrimaryKey(projectId);
        String status = projectselect.getStatus();
        if ("005".equals(status)) {
            // 如果是延期
            ZxProjectMilepost milepostYc = new ZxProjectMilepost();
            milepostYc.setProjectId(projectId);
            milepostYc.setFinishStatus("3");
            int countjd = zxProjectMilepostService.selectCount(milepostYc);
            if (countjd == 0) {
                //修改回原状态
                if (projectselect.getFinishDate() != null) {
                    //003 已完成
                    projectselect.setStatus("003");
                } else if (projectselect.getStartTime() != null) {
                    //004 进行中
                    projectselect.setStatus("004");
                } else if (projectselect.getCommitDate() != null) {
                    //002 未启动
                    projectselect.setStatus("002");
                } else {
                    //001 未提交
                    projectselect.setStatus("001");
                }
                zxProjectService.updateByPrimaryKey(projectselect);
            }


        }


    }



    /**
     * @param re
     * @param fileTypePt
     * @param fileType
     * @param jsonObject
     * @param fs_status
     * @param typeNum
     * @param projectId
     * @param stageId
     * @param spm_Id
     * @param stagef
     * @param request
     * @Author:zhaoyongke
     * @Description:完成状态的处理
     * @Date:16:11 2021/1/24
     */
    public String updateFinishSt(JsonUtil re, String fileTypePt, String fileType, JSONObject jsonObject, String fs_status, Integer typeNum, String projectId, String stageId, String spm_Id, ZxProjectStage stagef, HttpServletRequest request) throws Exception {
        String restr = "";
//        if (StringUtils.isNotBlank(checkPackageFile.getProjectId())) {
//            boolean atLeastOne = projectContractService.checkFileAtLeastOne(checkPackageFile);
//            if (!atLeastOne) {
//                restr = "有未完成的分包";
//                return restr;
//            }
//        }
        ZxProject zxProject = zxProjectService.selectByPrimaryKey(projectId);
        ZxProjectMilepost zxProjectMilepost = zxProjectMilepostService.selectByPrimaryKey(spm_Id);
        if(!("001".equals(zxProject.getIsContinue()) && ("001".equals(zxProjectMilepost.getMilepostNo())))){
            /*验证文件类型 必须包含一个文件*/
            if (StringUtil.isNotBlank(fileTypePt)) {
                ZxProjectDTO supervisorPro = new ZxProjectDTO();
                supervisorPro.setType(fileTypePt);
                boolean necessary = zxProjectService.checkFileNecessary(supervisorPro);
                if (necessary) {
                    /*需要校验文件*/
                    SupervisorFile checkFile = new SupervisorFile();
                    checkFile.setType(fileTypePt);
                    checkFile.setProjectId(projectId);
                    checkFile.setSpmId(spm_Id);
                    int countfile = supervisorFileService.selectCount(checkFile);
                    if (countfile == 0) {
                        restr = "请上传文件后，再完成";
                        return restr;
                    }
                }
            }
        }
        // 查询；里程表
        ZxProjectMilepost milepost = new ZxProjectMilepost();
        milepost.setId(spm_Id);
        milepost = zxProjectMilepostService.selectByPrimaryKey(milepost);
        String mepostNo = milepost.getMilepostNo();// 里程编号
        String step_num = milepost.getStepNum();
        // 数据库取出的完成状态
        String finishstatus = milepost.getFinishStatus();
        Integer num = 0;
        String[] ayStatus = step_num.split(",");
        String asPostStartIdx = fs_status.substring(0, 1);// 例如  10  20  截取  为  1 , 2
        //不是完成状态 则修改为完成状态
        if (!ayStatus[Integer.valueOf(asPostStartIdx) - 1].substring(1, 2).equals("2")) {
            ayStatus[Integer.valueOf(asPostStartIdx) - 1] = fs_status;// 数组更新状态
            String str = Arrays.toString(ayStatus).replace("[", "").replace("]", "").replace(" ", "");
            milepost.setStepNum(str);
            // 更新状态字符串
            zxProjectMilepostService.updateByPrimaryKey(milepost);
        }
        if ("003".equals(mepostNo)) {
            //项目咨询专用章授权书（可选）
            ayStatus[1] = "22";
        } else if ("007".equals(mepostNo)) {
            //评审记录--专家意见
            ayStatus[0] = "12";
        }
        for (int i = 0; i < ayStatus.length; i++) {// 判断是否都完成以2结尾的数量统计
            if (ayStatus[i].trim().substring(1, 2).equals("2")) {
                num++;
            }
        }
        // （1）本文件状态完成
        jsonObject.put("wj_status", "2");
        // （2）下面处理里程的状态
        if (!"2".equals(finishstatus)) { // 如果前台传入的文件类型和遍历计算的数量一致 则修改里程为已经完成
            if (typeNum == num) {
                /*判断里程是否延期*/
                /*里程完成*/
                milepost.setFinishStatus("2");
                milepost.setFinishDate(DateUtil.getCurrentDateString());
                zxProjectMilepostService.updateByPrimaryKey(milepost);
                /*监理通知文档合并*/
//                updatedohbwd(milepost);
                // 该里程完成
                jsonObject.put("lc_status", "2");
                //如果该里程是合同，那么更改项目状态为进行中
               zxProjectService.updateProjectStatusAfterMilepostFinish(milepost);
            } else {
                // 如果状态是0 侧修改成进行中
                if ("0".equals(milepost.getFinishStatus())) {
                    milepost.setFinishStatus("1");
                    zxProjectMilepostService.updateByPrimaryKey(milepost);
                    // 该里程为进行中
                    jsonObject.put("lc_status", "1");
                }
            }
        } else {
            // 如果是已经完成 则不用修改状态

        }
        // （3）下面处理 阶段的状态  该阶段下所有的里程都完成后 ，该阶段完成
        // 获得阶段
        Example example = new Example(SupervisorProjectMilepost.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("supervisorProjectStageId", stageId);
        criteria.andIsNull("finishDate");
         /*       criteria.andNotEqualTo("finishStatus", "2");//  2 是 已完成
                criteria.andNotEqualTo("finishStatus", "3");//  3 是 延迟*/
        // example.setOrderByClause("status  desc ");
        Integer count = zxProjectMilepostService.selectCountByExample(example);

        /*阶段编号*/
        String stageNo = stagef.getStageNo();
        Boolean qtIsfinsih = false;
        //注意：其他监理工作阶段  项目会议和监理周报 这两个里程碑完成后，整个阶段就设置完成状态
        if ("005".equals(stageNo)) {
            // 查询项目会议和监理周报 是否完成
            Example exampleLc = new Example(SupervisorProjectMilepost.class);
            Example.Criteria criteriaLc = exampleLc.createCriteria();
            Example.Criteria criteria2 = exampleLc.and();
            criteriaLc.andEqualTo("supervisorProjectStageId", stageId);
            criteria.andIsNull("finishDate");
            // criteriaLc.andNotEqualTo("finishStatus", "2");//   2 是 已完成
            criteria2.orEqualTo("milepostNo", "027");//项目会议
            criteria2.orEqualTo("milepostNo", "028");//监理周报
            int countqt = zxProjectMilepostService.selectCountByExample(exampleLc);
            if (countqt == 0) {
                qtIsfinsih = true;
            }
        }
        // 所有的都是已经完成
        if (count == 0 || qtIsfinsih) {
            // 更新
            /*阶段完成*/
            String jdstatus = updategetjdStatus(stagef);
            stagef.setFinishStatus(jdstatus);
            stagef.setFinishDate(DateUtil.getCurrentDateString());
            jsonObject.put("jd_status", jdstatus);
            zxProjectStageService.updateByPrimaryKey(stagef);
            //如果该阶段是验收阶段，那么设置项目状态为结束
            zxProjectService.updateProjectStatusAfterStageFinish(stagef);
            if (!"005".equals(stagef.getStageNo())) {
                BigDecimal bigDecimal = zxProjectService.calProgress(stagef);
                jsonObject.put("progress", bigDecimal);
            }
        } else {
            String jd_status = stagef.getFinishStatus(); // 阶段完成状态
            if (jd_status.equals("0")) {
                // 未进行修改为进行中
                stagef.setFinishStatus("1");
                jsonObject.put("jd_status", "1");
                zxProjectStageService.updateByPrimaryKey(stagef);
            }
            if (StringUtils.isNotBlank(milepost.getFinishDate())
                    && ("2".equals(milepost.getFinishStatus()) || "3".equals(milepost.getFinishStatus()))
                    && !"005".equals(stagef.getStageNo())) {
                BigDecimal bigDecimal = zxProjectService.calProgress(milepost);
                jsonObject.put("progress", bigDecimal);
            }
        }
        return restr;
    }


    /**
     * @param stage
     * @Author:zhaoyongke
     * @Description:
     * @Date:13:06 2021/1/11
     */
    public String updategetjdStatus(ZxProjectStage stage) throws Exception {
        /*查询有没有延迟的里程  如果有 则 阶段延迟*/
        ZxProjectMilepost milepost = new ZxProjectMilepost();
        milepost.setSupervisorProjectStageId(stage.getId());
        milepost.setFinishStatus("3");
        int countyclc = zxProjectMilepostService.selectCount(milepost);
        if (countyclc > 0) {
            /*延迟*/
            return "3";
        } else {
            /*完成*/
            return "2";
        }
    }
    /**
     * @param dto
     * @param model
     * @Author:hanchen
     * @Description:用章记录
     * @Date:11:35 2021/1/12
     */
    @GetMapping(value = "viewSealReocrd")
    public String viewSealReocrd(ZxProjectDTO dto, Model model) {
        String projectId = dto.getProjectId();
        ZxProject project = zxProjectService.selectByPrimaryKey(projectId);
        model.addAttribute("projectId", projectId);
        model.addAttribute("project", project);
        return "/zx/projectManager/viewSealRecord";
    }

    /**
     * 下载文件权限控制
     */
    @GetMapping(value = "rightControl")
    @ResponseBody
    public JsonUtil rightControl(HttpServletRequest request) {
        JsonUtil re = new JsonUtil();
        String id = request.getParameter("id");// 文件id
        if (!StringUtil.isBlank(id)) {
            SupervisorFile supervisorFile = new SupervisorFile();
            supervisorFile.setId(id);
            supervisorFile = supervisorFileService.selectByPrimaryKey(supervisorFile);
//            String role = sysUserService.getUserRole(supervisorFile.getProjectId());
//            if ("cj".equals(role)) {
//                BaseDict wjdict = DictUtil.getDictByCode(DictTypes.WJ, supervisorFile.getType());
//                String level14 = wjdict.getBadtLevel14();
//                if (!StringUtil.isBlank(level14)) {
//                    if (level14.indexOf(role) < 0) {
//                        re.setMsg("您没有权限导出文档");
//                        re.setFlag(false);
//                        return re;
//                    }
//                } else {
//                    re.setMsg("您没有权限导出文档");
//                    re.setFlag(false);
//                    return re;
//                }
//            }
        }
        re.setMsg("导出成功");
        re.setFlag(true);
        return re;
    }

    /**
     * @param dto
     * @param model
     * @param page
     * @param limit
     * @Author:hanchen
     * @Description:查询用章记录
     * @Date:11:51 2021/1/12
     */
    @GetMapping(value = "querySealRecord")
    @ResponseBody
    public ReType querySealRecord(ProjectSealRecordDTO dto, Model model, String page, String limit) {
        List<ProjectSealRecordDTO> tList = null;
        Page<ProjectSealRecordDTO> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
        try {
            tList = projectSealRecordService.selectProjectSealRecordList(dto);
        } catch (MyException e) {
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), tList);
    }

    /**
     * @param dto
     * @param model
     * @Author:zhaoyongke
     * @Description:项目大事记
     * @Date:16:55 2021/1/11
     */
    @GetMapping(value = "viewBigEvent")
    public String viewBigEvent(ZxProjectDTO dto, Model model) {
        String projectId = dto.getProjectId();
        ZxProject project = zxProjectService.selectByPrimaryKey(projectId);
        model.addAttribute("projectId", projectId);
        model.addAttribute("project", project);
        // 项目经理才有权限修改 大事记
        String managerPerson = project.getProjectManagerPerson();
        String userId = CommonUtil.getUserId();
        if (userId.equals(managerPerson)) {
            model.addAttribute("show", "1");
        }
        return "/zx/projectManager/viewBigEvent";
    }
    /**
     * @param dto
     * @param model
     * @param page
     * @param limit
     * @Author:hanchen
     * @Description:查询大事记
     * @Date:18:47 2021/1/11
     */
    @GetMapping(value = "queryBigEvent")
    @ResponseBody
    public ReType viewBigEvent(ProjectBigEventDTO dto, Model model, String page, String limit) {
        List<ProjectBigEventDTO> tList = null;
        Page<ProjectBigEventDTO> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
        try {
            tList = projectBigEventService.selectProjectBigEventZx(dto);
        } catch (MyException e) {
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), tList);
    }
    /**
     * @Author:zhaoyongke
     * @Description: 更新大事记
     * @Date:18:47 2021/1/11
     */
    @PostMapping(value = "updateBigEvent")
    @ResponseBody
    public JsonUtil updateBigEvent(ProjectBigEventDTO dto) {
        JsonUtil re = new JsonUtil();
        try {
            String id = dto.getProEventId();
            String operDate = dto.getOperDate();
            ProjectBigEvent event = projectBigEventService.selectByPrimaryKey(id);
            event.setOldOperDate(event.getOperDate());
            event.setOperDate(operDate);
            event.setModifyBy(CommonUtil.getUserId());
            event.setModifyDate(DateUtil.getCurrentDateString());
            projectBigEventService.updateByPrimaryKey(event);
            re.setFlag(true);
            re.setMsg("擦作成功");
        } catch (Exception e) {
            e.printStackTrace();
            re.setFlag(false);
            re.setMsg("擦作失败：" + e.getMessage());
        }
        return re;
    }

    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description:取消修改
     * @Date:17:41 2021/1/11
     */
    @PostMapping(value = "updateCancleBigEvent")
    @ResponseBody
    public JsonUtil updateCancleBigEvent(ProjectBigEventDTO dto) {
        JsonUtil re = new JsonUtil();
        try {
            String id = dto.getProEventId();
            ProjectBigEvent event = projectBigEventService.selectByPrimaryKey(id);
            event.setOperDate(event.getOldOperDate());
            event.setModifyBy(CommonUtil.getUserId());
            event.setModifyDate(DateUtil.getCurrentDateString());
            projectBigEventService.updateByPrimaryKey(event);
            re.setFlag(true);
            re.setMsg("擦作成功");
        } catch (Exception e) {
            e.printStackTrace();
            re.setFlag(false);
            re.setMsg("擦作失败：" + e.getMessage());
        }
        return re;
    }

    /**
     * @Author:hanchen
     * @Description:获取项目大事记 导出
     * 2021年11月25日15:07:35 修改为@Excel注解导出excel
     * @Date:18:39 2021年7月2日09:44:36
     */
    @GetMapping(value = "getBigEventData")
    @ResponseBody
    public void getBigEventData(ProjectBigEventDTO bigEvent, HttpServletResponse response) {
        String projectId = bigEvent.getProjectId();
        try {
            ZxProject zxProject = zxProjectService.selectByPrimaryKey(projectId);
            String name = zxProject.getProjectName() + "_项目大事记";
            List<ProjectBigEventDTO> tList = projectBigEventService.selectProjectBigEventZx(bigEvent);
            List<ExProjectBigEvent> temp = new ArrayList<>();
            for (int i = 0; i < tList.size(); i++) {
                ProjectBigEventDTO projectBigEventDTO = tList.get(i);
                ExProjectBigEvent exProjectBigEvent = new ExProjectBigEvent();
                exProjectBigEvent.setXh(String.valueOf(i+1));
                exProjectBigEvent.setStageName(projectBigEventDTO.getStageName());
                exProjectBigEvent.setMilePostName(projectBigEventDTO.getMilePostName());
                exProjectBigEvent.setOperDate(projectBigEventDTO.getOperDate());
                temp.add(exProjectBigEvent);
            }
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(name,name), ExProjectBigEvent.class, temp);
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name+".xls", "UTF-8"));
            workbook.write(response.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * @param dto
     * @param model
     * @Author:hanchen
     * @Description: 文档统计
     * @Date:16:10 2021年7月2日09:44:36
     */
    @GetMapping(value = "viewTj")
    public String viewTj(SupervisorProjectDTO dto, Model model) {
        String projectId = dto.getProjectId();
        ZxProject project = zxProjectService.selectByPrimaryKey(projectId);
        model.addAttribute("projectId", projectId);
        model.addAttribute("project", project);
        return "/zx/projectManager/view_tj";
    }

    /**
     * @param project
     * @param model
     * @param page
     * @param limit
     * @Author:hanchen
     * @Description: 统计文档类型
     * @Date:16:49 2021年7月2日09:44:36
     */
    @GetMapping(value = "showviewTjList")
    @ResponseBody
    public ReType showviewTjList(SupervisorProjectDTO project, Model model, int page, int limit) {
        String projectId = project.getProjectId();
        List<SupervisorFileDTO> tList = null;
        Page<SupervisorFileDTO> tPage = PageHelper.startPage(page, limit);
        try {
            SupervisorFileDTO dto = new SupervisorFileDTO();
            dto.setProjectId(projectId);
            tList = supervisorFileService.getzxFileCountByType(dto);
        } catch (MyException e) {
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), tList);
    }

    /**
     * @param project
     * @Author:hanchen
     * @Description: 导出数据
     * @Date:18:28 2021年7月2日09:44:36
     */
    @GetMapping(value = "getTjData")
    @ResponseBody
    public JsonUtil getTjData(SupervisorProjectDTO project) {
        JsonUtil re = new JsonUtil();
        String projectId = project.getProjectId();
        if (StringUtils.isEmpty(projectId)) {
            return JsonUtil.error("获取数据失败");
        } else {
            SupervisorFileDTO dto = new SupervisorFileDTO();
            dto.setProjectId(projectId);
            List<SupervisorFileDTO> tList = supervisorFileService.getFileCountByTypeZx(dto);
            re.setFlag(true);
            re.setData(tList);
        }
        return re;
    }
    /**
    * @Author:mr.hanchen
    * @Description:修改记录
    * @param pid
        * @param model
    * @Date:13:19 2021/7/2
    */
    @RequestMapping("/showProjectModRecord")
    public String showProjectModRecord(String pid, Model model) {
        if (StringUtils.isBlank(pid)) {
            model.addAttribute("message", "参数异常");
            return "/error/500";
        }
        model.addAttribute("spId", pid);
        return "/zx/projectManager/mod-record";
    }

    /**
    * @Author:mr.hanchen
    * @Description:修改记录
    * @param record
        * @param model
        * @param page
        * @param limit
    * @Date:13:21 2021/7/2
    */
    @ResponseBody
    @RequestMapping("/gerRecordList")
    public ReType gerRecordList(ZxProjectModifiedRecord record, Model model, int page, int limit) {
        List<ZxProjectModifiedRecord> tList = null;
        Page<AffairCaseDTO> tPage = PageHelper.startPage(page, limit);
        try {
            tList = modifiedRecordService.selectListByPage(record);
        } catch (MyException e) {
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), tList);
    }


    /**
     * @param id
     * @param request
     * @param response
     * @Author:Zhangshuo
     * @Description:
     * @Date:15:20 2020-12-14
     */
    @RequestMapping(value = "/export")
    public void downloadxls(@RequestParam("id") String id, @RequestParam("name") String name, HttpServletRequest request, HttpServletResponse response) throws IOException {
        SupervisorFileDTO dto = new SupervisorFileDTO();
        dto.setProjectId(id);
        /*查询监理文档---文件字典level4为1*/
        List<SupervisorFileDTO> AlstFiles = supervisorFileService.selectFileListZx(dto);
        // 获取项目名称
        ZxProject project = zxProjectService.selectByPrimaryKey(id);
        /*项目名称*/
        String projectName = project.getProjectName();
        String AsOutPath = tempPath + File.separator + name + DateUtil.getCurrentDateTimeStringNoSpliter() + ".zip";
        ZipOutputStream AzOut = new ZipOutputStream(new FileOutputStream(AsOutPath));
        try {
            for (SupervisorFileDTO AoFile : AlstFiles) {
                String AsTmpFileName = AoFile.getUrl();
                File AfTmp = new File(AsTmpFileName);
                if (AfTmp.exists()) {
                    Boolean isGl = true;
                    if (isGl) {
                        String path = AfTmp.getPath();
                        String fileName = AfTmp.getName();
                        String dir = path.substring(path.indexOf(projectName), path.length()).replace(projectName + "" + File.separator, "").replace(File.separator + "" + fileName, "");
                        ZipUtils.doCompress(new File(AsTmpFileName), AzOut, dir);
                    }

                }
            }
        } finally {
            AlstFiles.clear();
            AlstFiles = null;
            AzOut.close();
        }
        ExportFileUtil.exportFile(response, request, AsOutPath);
    }
    /**
     * @Author:mr.hanchen
     * @Description:修改记录
     * @param id
     * @param model
     * @param page
     * @param limit
     * @Date:13:21 2021/7/2
     */
    @ResponseBody
    @RequestMapping("/gerRecordListHk")
    public ReType gerRecordListHk(String id, Model model, int page, int limit) {
        List<ZxPayRecordDTO> tList = null;
        Page<ZxPayRecordDTO> tPage = PageHelper.startPage(page, limit);
        try {
            ZxProjectDTO zx = new ZxProjectDTO();
            zx.setId(id);
            tList = zxPayRecordService.selectHk(zx);
        } catch (MyException e) {
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), tList);
    }
    /**
     * @Author:mr.hanchen
     * @Description:修改记录
     * @param id
     * @Date:13:21 2021/7/5
     */
    @ResponseBody
    @RequestMapping("/gerRecordHk")
    public ZxPayRecordDTO gerRecordHk(String id) {
        ZxPayRecordDTO  tList = zxPayRecordService.selectHkById(id);
        ZxProjectPayDTO zxProjectPayDTO = new ZxProjectPayDTO();
        zxProjectPayDTO.setSppPrjid(tList.getProjectId());
        List<ZxProjectPayDTO> zxProjectPay = zxProjectPayService.selectSupervisorProjectPay(zxProjectPayDTO);
        for (ZxProjectPayDTO zx:
             zxProjectPay) {
            zx.setSppNo(getInteger(zx.getSppNo()));
        }
        tList.setZxProjectPayDTOS(zxProjectPay);
        return tList;
    }
    /**
     * @Author:mr.hanchen
     * @Description:保存是否到账
     * @param dto
     * @Date:13:21 2021/7/5
     */
    @ResponseBody
    @RequestMapping("/updateDz")
    public JsonUtil updateDz(ZxPayRecordDTO dto) {
        JsonUtil json = new JsonUtil();
        json.setFlag(false);
        try {
            ZxPayRecord zxPayRecord = new ZxPayRecord();
            zxPayRecord.setPayId(dto.getPayId());
            zxPayRecord = zxPayRecordService.selectByPrimaryKey(zxPayRecord);
            zxPayRecord.setIsArrival(dto.getIsArrival());
            zxPayRecord.setArrivalDate(dto.getArrivalDate());
            zxPayRecordService.updateByPrimaryKey(zxPayRecord);
        } catch (MyException e) {
            e.printStackTrace();
            json.setFlag(false);
            json.setMsg("操作失败!!!"+e.getMessage());
            return json;
        }
        json.setFlag(true);
        json.setMsg("操作成功");
        return json;
    }
    /**
     * @param filedata
     * @param dto
     * @param request
     * @Author:zhaoyongke
     * @Description: 上传附件
     * @Date:9:59 2021/1/14
     */
    @RequestMapping(value = "/addFileFj", method = RequestMethod.POST)
    @ResponseBody
    public JsonUtil addFileFj(@RequestParam(value = "file", required = false) MultipartFile filedata, ZxProjectDTO dto, HttpServletRequest request) {

        JsonUtil re = new JsonUtil();
        // 当前用户信息
        String filename = null;
        SupervisorFile filedto = null;
        try {
            String userid = CommonUtil.getUserId();
            String spmid = dto.getSpmId();// 里程id
            String stageId = dto.getStageId();//阶段id
            String projectid = dto.getId();// 项目id
            String fbId = request.getParameter("fbId");// 分包表id
            LoadType loadType = uploadUtil.upload(filedata, "1");
            filename = filedata.getOriginalFilename();
            // 保存文件表
            filedto = new SupervisorFile();
            if ("115".equals(dto.getType())) {
                /*监理工作总结报告*/
                filedto.setFileName(loadType.getFileName());
            } else {
                filedto.setFileName(filename);
            }

            filedto.setFileType(loadType.getSuffix());
            filedto.setType(dto.getType());
            filedto.setCreateBy(userid);
            filedto.setCreateDate(new Date());
            filedto.setUrl(loadType.getFilePath());
            if (null != fbId && !"".equals(fbId)) {
                filedto.setPcId(fbId);// 分包id
            }
            filedto.setParentId(dto.getParentId());
            if (!"113".equals(dto.getType())) {
                /*签章图片不保存 阶段和里程*/
                filedto.setSpmId(spmid);// 里程id
                filedto.setStageId(stageId);
            } else {
                // 校验格式

                System.out.println(loadType.getSuffix());
                if(!".jpg".equals(loadType.getSuffix().toLowerCase())  && !".png".equals(loadType.getSuffix().toLowerCase())  ){
                    re.setFlag(false);
                    re.setMsg("请上传jpg或png格式的图片");
                    return re;
                }





                /*删除之前的签章图片*/
                SupervisorFile file = new SupervisorFile();
                file.setProjectId(projectid);
                file.setType("113");
                List<SupervisorFile> filelist = supervisorFileService.select(file);
                for (int i = 0; i < filelist.size(); i++) {
                    File fileimage = new File(filelist.get(i).getUrl());
                    if (fileimage.exists()) {
                        fileimage.delete();
                        System.out.println("删除成功");
                    }
                    supervisorFileService.deleteByPrimaryKey(filelist.get(i));
                }
            }
            filedto.setProjectId(projectid);// 项目id
            supervisorFileService.insert(filedto);
            supervisorFileService.setFilePathDics(filedto);
            re.setData(filedto.getUrl());
            if ("115".equals(dto.getType())) {
                re.setMsg(loadType.getFileName());
            } else {
                re.setMsg(filename);
            }

            re.setFlag(true);
            return re;
        } catch (Exception e) {
            e.printStackTrace();
            re.setFlag(false);
        }

        return re;
    }
    /**
     * 小数点前面部分
     * @param num
     * @return
     */
    public static String getInteger(String num){
        String STR_UNIT[] = {"","拾","佰","仟","万","拾","佰","仟","亿"};
        String STR_NUMBER[] = {"零","一","二","三","四","五","六","七","八","九"};
        if (num.indexOf(".") != -1){
            num = num.substring(0, num.indexOf("."));
        }
        num = new StringBuffer(num).reverse().toString();
        StringBuffer temp = new StringBuffer();
        for (int i=0; i<num.length(); i++){
            temp.append(STR_UNIT[i]);
            temp.append(STR_NUMBER[num.charAt(i)-48]);
        }
        num = temp.reverse().toString();

        while (num.indexOf("零零") != -1 || num.indexOf("零佰") != -1 || num.indexOf("零仟") != -1 || num.indexOf("零万") != -1 || num.indexOf("零亿") != -1 || num.indexOf("亿万") != -1 || num.indexOf("零拾") != -1) {
            num = numReplace(num, "零拾", "零");
            num = numReplace(num, "零佰", "零");
            num = numReplace(num, "零仟", "零");
            num = numReplace(num, "零万", "万");
            num = numReplace(num, "零亿", "亿");
            num = numReplace(num, "零零", "零");
            num = numReplace(num, "亿万", "亿");
            if (num.lastIndexOf("零") == num.length() - 1) {
                num = num.substring(0, num.length() - 1);
            }
        }

        return num;
    }
    public static String numReplace(String num, String oldUnit, String newUnit){
        num = num.replaceAll(oldUnit,newUnit);
        return num;
    }

    /**
     * 查看是否是检测项目
     * @param projectId
     * @return
     */
    @GetMapping(value = "/selectProject")
    @ResponseBody
    public Boolean selectProject(String projectId){
        ZxProject zx=new ZxProject();
        int i=0;
        if(StringUtils.isNotBlank(projectId)) {
            zx.setId(projectId);
            i = zxProjectService.selectCount(zx);
        }
        if(i>0){
            return true;
        }else{
            return false;
        }
    }

    /**
     * @param project
     * @param model
     * @param page
     * @param limit
     * @Author:zhaoyongke
     * @Description:
     * @Date:16:45 2021/3/13
     */
    @ApiOperation(value = "/showProjectGxList", httpMethod = "GET", notes = "展示供需项目")
    @GetMapping(value = "/showProjectGxList")
    @ResponseBody
    public ReType showProjectList(SupplierProjectDTO project, Model model, String page, String limit) {
        //已经结束状态
        ReType re = new ReType();
        project.setStatus("004");
        if(StringUtil.isNotBlank(project.getKeyword())){
            project.setProjectName(project.getKeyword());
        }
        project.setProjectType("002");
        //项目经理是自己的
//        project.setZxManagerPerson(CommonUtil.getUserId());
        List<SupplierProjectDTO> data = supplierProjectManagerService.selectListGx(project);
        for (int i = 0; i < data.size(); i++) {
            SupplierProjectDTO dto = (SupplierProjectDTO) data.get(i);
            String pubComType = dto.getPubComType();
            String publishBy = dto.getPublishBy();
            // 中标人
            String zbBy = dto.getZbBy();
            String supAcceptId = dto.getSupAcceptId();
            //客户名称
            String owerCompany = dto.getOwerCompany();
            SupplierProjectAccept accept = supplierProjectAcceptService.selectByPrimaryKey(supAcceptId);

            String companyId = accept.getCompanyId();
            // 获取业主单位
            String    companyName=getFbdwByUser(publishBy,owerCompany);



            data.get(i).setCompanyName(companyName);
            data.get(i).setZbCompany(companyId);
            data.get(i).setZxManagerPerson(accept.getJcManagerPerson());
            ProjectPlaceDTO pacedto = new ProjectPlaceDTO();
            pacedto.setSupProjectId(dto.getSupProjectId());
            pacedto.setType("001");
            List<ProjectPlaceDTO> listpalce = projectPlaceService.selectPlace(pacedto);
            for (int y = 0; y < listpalce.size(); y++) {
                String province = listpalce.get(y).getProvince();
                List<SysRegion> citylist1 = sysRegionService.selectSysRegionByParentCode(province);
                listpalce.get(y).setCitys(citylist1);
                String city = listpalce.get(y).getCity();
                List<SysRegion> countylist2 = sysRegionService.selectSysRegionByParentCode(city);
                listpalce.get(y).setCountys(countylist2);
            }
            data.get(i).setProjectPlacedtos(listpalce);


            // 中标单位
     /*        String  zbCompanyName=getAcceptdwByUser(accept);
             data.get(i).setZbCompanyName(zbCompanyName);*/

        }
        re.setPageNum(Long.valueOf(page));
        re.setCount(data.size());
        re.setData(data);

        return re;

    }

    /**
     * @param userId
     * @Author:zhaoyongke
     * @Description: 获取发布单位
     * @Date:10:24 2021/4/7
     */
    public String getFbdwByUser(String userId,String khmc) {
        String companyName = "";
        SysUser sysUser = sysUserService.selectByPrimaryKey(userId);
        String source = sysUser.getSource();
        if ("001".equals(source)) {
            if(StringUtil.isNotBlank(khmc)){
                // 获取选择的oa 接口中的数据
                companyName=khmc;
            }else{
                // 正中人员
                String companyId = sysUser.getCompanyName();
                BaseCompany baseCompany = baseCompanyService.selectByPrimaryKey(companyId);
                companyName = baseCompany.getBcName();
            }

        } else {
            companyName = sysUser.getCompanyName();
        }
        return companyName;

    }


    /**
     * @param dto
     * @param model
     * @param page
     * @param limit
     * @Author:zhaoyongke
     * @Description: 查询文件列表
     * @Date:9:58 2020/11/27
     */
    @RequestMapping(value = "/showFileList", method = RequestMethod.GET)
    @ResponseBody
    public ReType showFileList(SupervisorProjectDTO dto, Model model, String page, String limit) {

        ReType re = new ReType();
        String uploadType = dto.getUploadType();
        SupervisorFile file = new SupervisorFile();
        List<SupervisorFile> list =null;
        if("020".equals(dto.getType())){
            Example ex=new Example(SupervisorFile.class);
            Example.Criteria cr = ex.createCriteria();
            cr.andNotEqualTo("type","113");
            cr.andEqualTo("parentId",dto.getParentId());
            list = supervisorFileService.selectByExample(ex);
        }else{
            if ("002".equals(uploadType)) {// 每个文件下面有图片 根据 parentId 查询  例如 检查旁站 每个文件下的图片列表
                file.setParentId(dto.getParentId());
            } else {//
                file.setProjectId(dto.getProjectId());
                file.setSpmId(dto.getSpmId());
                file.setPcId(dto.getFbId());
                file.setType(dto.getType());
            }
            list = supervisorFileService.select(file);
//        for (int i = 0; i < list.size(); i++) {
//            String url = list.get(i).getUrl();
//            //获取文件名称
//            if (StringUtil.isNotBlank(url)) {
//                String urlz = FilePathUtil.getFileName(url);
//                list.get(i).setUrl(urlz);
//            }
//        }
        }

        re.setData(list);
        return re;
    }

    @GetMapping(value = "/selectFileQz")
    @ResponseBody
    public  JsonUtil selectFileQz(String fileId){
        JsonUtil re = new JsonUtil();
        if(StringUtil.isBlank(fileId)){
            re.setFlag(false);
            re.setMsg("获取文件失败");
            return re;
        }
        SupervisorFile supervisorFile = supervisorFileService.selectByPrimaryKey(fileId);
        if(supervisorFile!=null){
            String qzStatus = supervisorFile.getQzStatus();
            if("1".equals(qzStatus)){
                re.setFlag(true);
                re.setData("1");
                return re;

            }else{
                re.setFlag(true);
                re.setData("");
                return re;
            }
        }else{
            re.setFlag(false);
            re.setMsg("获取文件失败");
            return re;
        }


    }
}
